package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"

	"my_code/biligoo/other"

	"github.com/BurntSushi/toml"
	"github.com/bitly/go-simplejson"
	"github.com/valyala/fastjson"
)

type roomidInfo struct {
	UID          int
	Uname        string
	Face         string
	Level        int
	OfficialType int
	OfficialDesc string
	OfficialRole int
}

var (
	RoomidInfos     = make(map[int]roomidInfo)
	RoomidInfosLock = &sync.Mutex{}
)
var TomlInfo = &MonToml{}

func getRoomidInfo(roomid int) (rI roomidInfo) {
	rI = roomidInfo{}
	RoomidInfosLock.Lock()
	defer RoomidInfosLock.Unlock()
	if ri, ok := RoomidInfos[roomid]; ok {
		rI = ri
		return
	}
	url := "https://api.live.bilibili.com/live_user/v1/UserInfo/get_anchor_in_room?roomid=" + strconv.Itoa(roomid)
	b, c := other.AppReqGet(url)
	if !c {
		return
	}
	rI.UID = fastjson.GetInt(b, "data", "info", "uid")
	if rI.UID == 0 {
		return
	}
	rI.Uname = fastjson.GetString(b, "data", "info", "uname")
	rI.Face = fastjson.GetString(b, "data", "info", "face")
	rI.Level = fastjson.GetInt(b, "data", "info", "platform_user_level")
	rI.OfficialType = fastjson.GetInt(b, "data", "info", "official_verify", "type")
	rI.OfficialDesc = fastjson.GetString(b, "data", "info", "official_verify", "desc")
	rI.OfficialRole = fastjson.GetInt(b, "data", "info", "official_verify", "role")
	RoomidInfos[roomid] = rI
	return
}
func init() {
	go func() {
		for {
			time.Sleep(time.Second * 30)
			TomlInfo = ReadToml()
		}
	}()
	TomlInfo = ReadToml()
	ACCESS = TomlInfo.User.Access
	UID = TomlInfo.User.UID
	go func() {
		for {
			time.Sleep(time.Second * 10)
			TomlInfo = ReadToml()
			ACCESS = TomlInfo.User.Access
			UID = TomlInfo.User.UID
		}
	}()
	b, _ := other.AppReqGet("https://app.bilibili.com/x/v2/account/mine?" + other.Sign("access_key="+ACCESS+"&appkey=1d8b6e7d45233436&bili_link_new=1&build=7480200&c_locale=zh_CN&channel=huawei&disable_rcmd=0&from=mine&mobi_app=android&platform=android&s_locale=zh_CN&statistics=%7B%22appId%22%3A1%2C%22platform%22%3A3%2C%22version%22%3A%227.48.0%22%2C%22abtest%22%3A%22%22%7D&ts="+other.StrTime()))
	name := fastjson.GetString(b, "data", "name")
	if name == "" {

		fmt.Print("请输入手机号:")
		tel := ""
		inputChan := make(chan string, 1)

		// 启动一个 goroutine 读取用户输入
		go func() {
			reader, err := bufio.NewReader(os.Stdin).ReadString('\n')
			if err == nil {
				inputChan <- strings.TrimSpace(reader)
			} else {
				inputChan <- ""
			}
		}()
		select {
		case <-time.After(30 * time.Second):
			fmt.Println("超时: 30秒内未输入")
			return
		case tel = <-inputChan:
		}
		if tel == "" {
			return
		}
		ACCESS, _, _, _ = LoginSmsByPrint(tel)
		b, _ := other.AppReqGet("https://app.bilibili.com/x/v2/account/mine?" + other.Sign("access_key="+ACCESS+"&appkey=1d8b6e7d45233436&bili_link_new=1&build=7480200&c_locale=zh_CN&channel=huawei&disable_rcmd=0&from=mine&mobi_app=android&platform=android&s_locale=zh_CN&statistics=%7B%22appId%22%3A1%2C%22platform%22%3A3%2C%22version%22%3A%227.48.0%22%2C%22abtest%22%3A%22%22%7D&ts="+other.StrTime()))
		name = fastjson.GetString(b, "data", "name")
		TomlInfo.User.Access = ACCESS
		TomlInfo.WriteToml()
	}
	fmt.Println("登录账号:", name)
}
func getRoom() (roomids []int) {
	roomids = []int{}
	t := ReadToml()
	ACCESS = t.User.Access
	UID = t.User.UID
	//fmt.Println(ACCESS, UID)
	TomlInfo = t
	pageStart, pageEnd := t.PageRange[0], t.PageRange[1]
	//pageSize := t.PageSize
	runs := []string{"-", "\\", "|", "/"}
	for page := pageStart; page <= pageEnd; page++ {
		fmt.Printf("\r%v正在查询第%v页，已获得%v个房间      ", runs[page%len(runs)], page, len(roomids))
		//url := "https://api.live.bilibili.com/room/v1/Area/getListByAreaID?areaId=0&sort=online&platform=web&pageSize=" + strconv.Itoa(t.PageSize) + "&page=" + strconv.Itoa(page)
		//url := "https://api.live.bilibili.com/xlive/web-interface/v1/second/getListByArea?sort=online&page=" + strconv.Itoa(page) + "&page_size=30&platform=web"
		//https://api.live.bilibili.com/xlive/web-interface/v1/second/getListByArea?sort=online&page=1&page_size=30&platform=web
		//https://api.live.bilibili.com/xlive/web-interface/v1/second/getUserRecommend?page=1&page_size=30&platform=web
		url := "https://api.live.bilibili.com/xlive/web-interface/v1/second/getUserRecommend?page=" + strconv.Itoa(page) + "&page_size=30&platform=web"
		b, c := other.AppReqGet(url)
		if !c {
			return
		}
		//fmt.Println(url, "\n", string(b))
		js, err := simplejson.NewJson(b)
		if err != nil {
			return
		}
		//[0].roomid
		list, err := js.Get("data").Get("list").Array()
		if err != nil {
			fmt.Println("getRoomid json data err:", err)
			return
		}
		if len(list) == 0 {
			break
		}
		for i := range list {
			roomid, err := js.Get("data").Get("list").GetIndex(i).Get("roomid").Int()
			if err != nil {
				fmt.Println("getRoomid json data.x.roomid err:", err)
				return
			}
			roomids = append(roomids, roomid)
		}
		has_more, err := js.Get("data").Get("has_more").Int()
		if err == nil && has_more == 0 {
			break
		}
		//time.Sleep(time.Second / 10)
	}
	fmt.Printf("\r%v从%v页中找到%v个房间                 ", other.TI(), pageEnd-pageStart+1, len(roomids))
	/*roommap := map[int]int{}
	for _, v := range roomids {
		if _, ok := roommap[v]; !ok {
			roommap[v] = 1
		} else {
			roommap[v] = roommap[v] + 1
		}

	}
	for k, v := range roommap {
		if v != 1 {
			fmt.Println(k, v)
		}
	}
	fmt.Println(roommap)*/
	return
}

type MonToml struct {
	PageRange [2]int
	//PageSize  int
	MaxRoom  int
	POST     PostInfo
	User     UserInfo
	GiftList []string
}

type PostInfo struct {
	Anchor bool
	Storm  bool
	PopRed bool
	Red    bool
}
type UserInfo struct {
	Access string
	UID    int
}

var tomlFilePath string = "./monitor.toml"

// WriteToml ...
func (T *MonToml) WriteToml() {
	f, err := os.Create(tomlFilePath)
	if err != nil {
		fmt.Println(err)
		return
	}
	if err := toml.NewEncoder(f).Encode(T); err != nil {
		fmt.Println(err)
		return
	}
}
func ReadToml() (config *MonToml) {
	if _, err := os.Stat(tomlFilePath); err != nil {
		c := PostInfo{true, true, true, true}
		u := UserInfo{"", 0}
		s := MonToml{PageRange: [2]int{1, 10}, MaxRoom: 10, POST: c, User: u, GiftList: []string{"浪漫城堡", "荣光之炬", "焰皇神碑", "龙啸之炎", "荣誉之焰", "棉花糖", "焰心火石", "BW舞台", "时空之站", "BW权杖", "BW蛋糕", "电影票"}}
		s.WriteToml()
	}
	if _, err := toml.DecodeFile(tomlFilePath, &config); err != nil {
		fmt.Println(other.TI() + "请检查配置文件！")
		time.Sleep(time.Second)
		panic(err)
	}
	return
}
